package com.hdu.dwh.controller;

import com.amazonaws.services.dynamodbv2.xspec.L;
import com.hdu.dwh.annotation.RequirePermission;
import com.hdu.dwh.dtos.user_dtos.*;
import com.hdu.dwh.pojos.SupersetUser;
import com.hdu.dwh.pojos.User;
import com.hdu.dwh.results.ResponseResult;
import com.hdu.dwh.service.SupersetRestService;
import com.hdu.dwh.service.UserService;
import com.hdu.dwh.utils.AppJwtUtil;
import com.hdu.dwh.utils.SupersetUtils;
import com.hdu.dwh.vos.UserVo.LoginVo;
import com.hdu.dwh.vos.UserVo.UserOperationVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
@Tag(name = "[产品]用户", description = "用户管理接口")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private SupersetRestService supersetRestService;

    @Operation(summary = "用户注册", description = "创建新用户")
    @PostMapping("/register")
    public ResponseResult<User> register(@RequestBody RegisterUserDto user) {
        try {
            SupersetUser supersetUser = SupersetUtils.convertToSupersetUser(user);
            MultiValueMap<String, String> form = SupersetUtils.convertToRegisterForm(supersetUser);
            ResponseEntity<String> responseEntity = this.supersetRestService.createSupersetUser(form);
            if (!(responseEntity.getStatusCode().is2xxSuccessful() || responseEntity.getStatusCode().is3xxRedirection())) {
                throw new RuntimeException("Superset 用户注册失败, 状态码: " + responseEntity.getStatusCode());
            }
            return userService.register(user.getUsername(), user.getPassword());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(500, e.getMessage());
        }
    }

    /**
     * 用户登录
     */
    @Operation(summary = "用户登录", description = "用户身份验证")
    @PostMapping("/login")
    public ResponseResult<LoginVo> login(@RequestBody LoginUserDto user) {
        try {
            ResponseResult<User> result = userService.login(user.getUsername(), user.getPassword());
            if (result.getCode() == 200) {
                // 获取用户信息
                User userInfo = userService.getUserByUsername(user.getUsername());
                
                if (userInfo != null) {
                    // 登录成功，生成包含用户类型的 token
                    String token = AppJwtUtil.generateToken(
                            String.valueOf(userInfo.getUserid()),
                            userInfo.getUsername(),
                            userInfo.getUsertype());

                    // 创建LoginVo对象并设置token和用户信息
                    LoginVo loginVo = new LoginVo();
                    loginVo.setToken(token);
                    loginVo.setUserid(userInfo.getUserid());
                    loginVo.setUsername(userInfo.getUsername());
                    loginVo.setUsertype(userInfo.getUsertype());

                    return ResponseResult.success("登录成功", loginVo);
                    // 这里可以根据需要将token放入响应头或创建专门的VO对象
                    // 目前保持service层返回结果不变
                }
            }

            // 登录失败，返回原始错误信息
            return ResponseResult.fail(result.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(500, e.getMessage());
        }
    }

    /**
     * 修改密码
     */
    @Operation(summary = "修改密码", description = "更新用户密码")
    @PostMapping("/update_password")
    public ResponseResult<UserOperationVo> updatePassword(@RequestBody UpdatePasswordDto user) {
        try {
            // 使用用户名和新密码来更新
            return userService.updatePassword(user.getUsername(), user.getPassword());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(500, e.getMessage());
        }
    }

    /**
     * 删除用户
     */
    @Operation(summary = "删除用户", description = "删除指定用户名的用户")
    @DeleteMapping("/delete")
    @RequirePermission("user.manage") // 添加权限注解
    public ResponseResult<UserOperationVo> deleteUser(@RequestBody DeleteUserDto user) {
        try {
            return userService.deleteUser(user.getUsername());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(500, e.getMessage());
        }
    }

    /**
     * 查询用户列表
     */
    @Operation(summary = "获取用户列表", description = "获取用户列表")
    @GetMapping("/listUser")
    @RequirePermission("user.manage") // 添加权限注解
    public ResponseResult<List<User>> getUserList() {
        return ResponseResult.success("查询成功", userService.list());
    }

    /**
     * 修改用户权限 - 需要管理员权限
     */
    @Operation(summary = "修改用户权限", description = "修改用户权限")
    @PostMapping("/updateUsertype")
    @RequirePermission("user.manage") // 添加权限注解
    public ResponseResult<UserOperationVo> updateUsertype(@RequestBody UpdateUserTypeDto user) {
        try {
            return userService.updateUsertype(user.getUsername(), user.getUsertype());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(500, e.getMessage());
        }
    }

    @Operation(summary = "新增用户", description = "管理员新增用户")
    @PostMapping("/addUser")
    @RequirePermission("user.manage") // 添加权限注解
    public ResponseResult<UserOperationVo> addUser(@RequestBody RegisterUserDto user) {
        try {
            return userService.addUser(user.getUsername(), user.getPassword(), user.getUsertype());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(500, e.getMessage());
        }
    }

}
